<template>
  <div class="gi_table_page">
    <GiTable
        row-key="id"
        :data="dataList"
        :columns="columns"
        :loading="loading"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="pagination"
        :disabled-tools="['size']"
        :disabled-column-keys="['name']"
        @refresh="search"
    >
      <template #toolbar-left>
        <a-input-search v-model="queryForm.title" placeholder="请输入标题或待办内容" allow-clear @search="search"/>
        <a-select
            v-model="queryForm.priority"
            :options="priority_type"
            placeholder="请选择优先级"
            allow-clear
            style="width: 150px"
            @change="search"
        />
        <a-select
            v-model="queryForm.status"
            :options="todo_status_enum"
            placeholder="待办状态"
            allow-clear
            style="width: 150px"
            @change="search"
        />
        <a-select
            v-model="queryForm.type"
            :options="todo_type"
            placeholder="待办类型"
            allow-clear
            style="width: 150px"
            @change="search"
        />
        <!--        <a-date-picker-->
        <!--            v-model="queryForm.remindTime"-->
        <!--            placeholder="待办开始时间"-->
        <!--            show-time-->
        <!--            format="YYYY-MM-DD HH:mm:ss"-->
        <!--            style="height: 32px"-->
        <!--            @change="search"-->
        <!--        />-->
        <a-button @click="reset">
          <template #icon>
            <icon-refresh/>
          </template>
          <template #default>重置</template>
        </a-button>
      </template>

      <template #toolbar-right>
        <a-button v-permission="['system:todo:create']" type="primary" @click="onAdd">
          <template #icon>
            <icon-plus/>
          </template>
          <template #default>新增</template>
        </a-button>
        <!--        <a-button v-permission="['system:todo:export']" @click="onExport">-->
        <!--          <template #icon>-->
        <!--            <icon-download/>-->
        <!--          </template>-->
        <!--          <template #default>导出</template>-->
        <!--        </a-button>-->
      </template>

      <template #title="{ record }">
        <a-typography-paragraph :ellipsis="{rows: 1,showTooltip: true,css: true}">
          {{ record.title }}
        </a-typography-paragraph>
      </template>

      <template #priority="{ record }">
        <GiCellTag :value="record.priority" :dict="priority_type"/>
      </template>

      <template #dealResult="{ record }">
        <GiCellTag :value="record.dealResult" :dict="todo_status_enum"/>
      </template>

      <template #businessType="{ record }">
        <GiCellTag :value="record.businessType" :dict="todo_business_enum"/>
      </template>

      <template #todoMethods="{ record }">
        <span v-if="!record.todoMethods">无</span>
        <GiCellTags v-else :data="formatTodoMethods(record.todoMethods)"/>
      </template>

      <template #type="{ record }">
        <GiCellTag :value="record.type" :dict="todo_type"/>
      </template>

      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['system:todo:get']" title="详情" @click="onDetail(record)">详情</a-link>
          <a-link v-permission="['system:todo:view']" title="待办处理" @click="onView(record)">处理</a-link>
          <a-dropdown v-permission="['system:todo:update', 'system:todo:delete']">
            <a-button v-if="has.hasPermOr(['system:todo:update', 'system:todo:delete'])" type="text" size="mini"
                      title="更多">
              <template #icon>
                <icon-more :size="16"/>
              </template>
            </a-button>
            <template #content>
              <a-doption v-permission="['system:todo:update']" v-if="record.type === '2'">
                <a-link title="修改" @click="onUpdate(record)">修改</a-link>
              </a-doption>
              <a-doption v-permission="['system:todo:delete']">
                <a-link status="danger" title="删除" @click="onDelete(record)">删除</a-link>
              </a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </GiTable>

    <TodoDetailDrawer ref="TodoDetailDrawerRef"/>
  </div>
</template>

<script setup lang="ts">
import type {TableInstance} from '@arco-design/web-vue'
import TodoDetailDrawer from './TodoDetailDrawer.vue'
import {type TodoResp, type TodoQuery, deleteTodo, exportTodo, listTodo} from '@/apis/system/todo'
import {useDownload, useTable} from '@/hooks'
import {useDict} from '@/hooks/app'
import {isMobile} from '@/utils'
import has from '@/utils/has'

defineOptions({name: 'Todo'})

const {
  todo_method_enum,
  priority_type,
  todo_type,
  todo_status_enum,
  todo_business_enum,
  todo_scope_enum
} = useDict('todo_method_enum', 'priority_type', 'todo_type', 'todo_status_enum', 'todo_business_enum', 'todo_scope_enum')

const router = useRouter()

const queryForm = reactive<TodoQuery>({
  title: undefined,
  content: undefined,
  priority: undefined,
  status: undefined,
  type: undefined,
  businessType: undefined,
  remindTime: undefined,
  startTime: undefined,
  endTime: undefined,
  todoScope: undefined,
  sort: ['priority,desc']
})

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete
} = useTable((page) => listTodo({...queryForm, ...page}), {immediate: true})


const columns: TableInstance['columns'] = [
  {
    title: '序号',
    width: 90,
    align: 'center',
    render: ({rowIndex}) => h('span', {}, rowIndex + 1 + (pagination.current - 1) * pagination.pageSize),
  },
  {title: '待办标题', dataIndex: 'title', slotName: 'title'},
  {title: '发布人', dataIndex: 'createUserString', maxWidth: 120, ellipsis: true, tooltip: true},
  {title: '待办优先级', dataIndex: 'priority', slotName: 'priority'},
  {title: '通知方式', dataIndex: 'todoMethods', slotName: 'todoMethods', maxWidth: 165, ellipsis: true, tooltip: true},
  {title: '待办状态', dataIndex: 'dealResult', slotName: 'dealResult'},
  {title: '待办类型', dataIndex: 'type', slotName: 'type'},
  {title: '业务类型', dataIndex: 'businessType', slotName: 'businessType'},
  // {title: '截止时间', dataIndex: 'endTime', slotName: 'endTime'},
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 160,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr(['system:todo:get', 'system:todo:update', 'system:todo:delete'])
  }
]

// 重置
const reset = () => {
  queryForm.title = undefined
  queryForm.priority = undefined
  queryForm.status = undefined
  queryForm.type = undefined
  queryForm.startTime = undefined
  queryForm.endTime = undefined
  queryForm.todoScope = undefined
  search()
}

// 删除
const onDelete = (record: TodoResp) => {
  return handleDelete(() => deleteTodo(record.id), {
    content: `是否确定删除该条数据？`,
    showModal: true
  })
}

// 导出
const onExport = () => {
  useDownload(() => exportTodo(queryForm))
}

const TodoAddModalRef = ref<InstanceType<typeof TodoAddModal>>()
// 新增
const onAdd = () => {
  router.push({path: '/system/todo/add'})
}

// 修改
const onUpdate = (record: TodoResp) => {
  TodoAddModalRef.value?.onUpdate(record.id)
}

const TodoDetailDrawerRef = ref<InstanceType<typeof TodoDetailDrawer>>()
// 详情
const onDetail = (record: TodoResp) => {
  TodoDetailDrawerRef.value?.onOpen(record.id)
}

// 查看 - 包含处理待办
const onView = (record: TodoResp) => {
  router.push({path: '/system/todo/view', query: {id: record.id}})
}

// 格式化通知方式（转换为GiCellTags所需格式）
const formatTodoMethods = (todoMethods: string[]) => {
  return todoMethods.map((method) => {
    const dictItem = todo_method_enum.value.find((item) => item.value === method)
    return dictItem?.label || method
  })
}
</script>

<style scoped lang="scss"></style>
